package com.jason.data;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * DatabaseUtil
 */
public class DatabaseUtil {
    private final static Logger LOGGER = LoggerFactory.getLogger(DatabaseUtil.class);

    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/app_weishijie_ne?useUnicode=true&characterEncoding=utf8";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    private static final String SQL = "SELECT * FROM ";// 数据库操作

    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            LOGGER.error("can not load jdbc driver", e);
        }
    }

    /**
     * 获取数据库连接
     *
     * @return
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            LOGGER.error("get connection failure", e);
        }
        return conn;
    }

    /**1
     * 关闭数据库连接
     * @param conn
     */
    public static void closeConnection(Connection conn) {
        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                LOGGER.error("close connection failure", e);
            }
        }
    }

    /**
     * 获取数据库下的所有表名
     */
    public static List<String> getTableNames() {
        List<String> tableNames = new ArrayList<>();
        Connection conn = getConnection();
        ResultSet rs = null;
        try {
            //获取数据库的元数据
            DatabaseMetaData db = conn.getMetaData();
            //从元数据中获取到所有的表名
            rs = db.getTables(null, null, null, new String[] { "TABLE" });
            while(rs.next()) {
                tableNames.add(rs.getString(3));
            }
        } catch (SQLException e) {
            LOGGER.error("getTableNames failure", e);
        } finally {
            try {
                rs.close();
                closeConnection(conn);
            } catch (SQLException e) {
                LOGGER.error("close ResultSet failure", e);
            }
        }
        return tableNames;
    }

    /**
     * 获取表中所有字段名称
     * @param tableName 表名
     * @return
     */
    public static List<String> getColumnNames(String tableName) {
        List<String> columnNames = new ArrayList<>();
        //与数据库的连接
        Connection conn = getConnection();
        PreparedStatement pStemt = null;
        String tableSql = SQL + tableName;
        try {
            pStemt = conn.prepareStatement(tableSql);
            //结果集元数据
            ResultSetMetaData rsmd = pStemt.getMetaData();
            //表列数
            int size = rsmd.getColumnCount();
            for (int i = 0; i < size; i++) {
                columnNames.add(rsmd.getColumnName(i + 1));
            }
        } catch (SQLException e) {
            LOGGER.error("getColumnNames failure", e);
        } finally {
            if (pStemt != null) {
                try {
                    pStemt.close();
                    closeConnection(conn);
                } catch (SQLException e) {
                    LOGGER.error("getColumnNames close pstem and connection failure", e);
                }
            }
        }
        return columnNames;
    }

    /**
     * 获取表中所有字段类型
     * @param tableName
     * @return
     */
    public static List<String> getColumnTypes(String tableName) {
        List<String> columnTypes = new ArrayList<>();
        //与数据库的连接
        Connection conn = getConnection();
        PreparedStatement pStemt = null;
        String tableSql = SQL + tableName;
        try {
            pStemt = conn.prepareStatement(tableSql);
            //结果集元数据
            ResultSetMetaData rsmd = pStemt.getMetaData();
            //表列数
            int size = rsmd.getColumnCount();
            for (int i = 0; i < size; i++) {
                String columType = rsmd.getColumnTypeName(i + 1).toLowerCase();
                if (!columType.equals("decimal")) {
                    columnTypes.add(rsmd.getColumnTypeName(i + 1).toLowerCase() + "("+ rsmd.getColumnDisplaySize(i + 1) +")");
                } else {
                    columnTypes.add(rsmd.getColumnTypeName(i + 1).toLowerCase() + "("+ rsmd.getColumnDisplaySize(i + 1)+"," + rsmd.getScale(i + 1) + ")");
                }

            }
        } catch (SQLException e) {
            LOGGER.error("getColumnTypes failure", e);
        } finally {
            if (pStemt != null) {
                try {
                    pStemt.close();
                    closeConnection(conn);
                } catch (SQLException e) {
                    LOGGER.error("getColumnTypes close pstem and connection failure", e);
                }
            }
        }
        return columnTypes;
    }

    /**
     * 获取是否为空属性
     * @param tableName
     * @return
     */
    public static List<String> getColumnIsNull(String tableName) {
        List<String> columnIsNull = new ArrayList<>();
        //与数据库的连接
        Connection conn = getConnection();
        PreparedStatement pStemt = null;
        String tableSql = SQL + tableName;
        try {
            pStemt = conn.prepareStatement(tableSql);
            //结果集元数据
            ResultSetMetaData rsmd = pStemt.getMetaData();
            //表列数
            int size = rsmd.getColumnCount();
            for (int i = 0; i < size; i++) {
                int nullValue = rsmd.isNullable(i + 1);
                //不能为null-->0  可以为null-->1
                if (nullValue == 0) {
                    columnIsNull.add("TRUE");
                } else {
                    columnIsNull.add("");
                }
            }
        } catch (SQLException e) {
            LOGGER.error("getColumnTypes failure", e);
        } finally {

            if (pStemt != null) {
                try {
                    pStemt.close();
                    closeConnection(conn);
                } catch (SQLException e) {
                    LOGGER.error("getColumnTypes close pstem and connection failure", e);
                }
            }
        }
        return columnIsNull;
    }

    /**
     * 获取字段设置的默认值
     * @param tableName
     * @return
     */
    public static List<String> getDefaultValue(String tableName) {
        List<String> columnDefaultValue = new ArrayList<>();
        //与数据库的连接
        Connection conn = getConnection();
        PreparedStatement pStemt = null;
        String tableSql = SQL + tableName;
        ResultSet rs = null;
        try {
            pStemt = conn.prepareStatement(tableSql);
            rs = pStemt.executeQuery("show full columns from " + tableName);
            while (rs.next()) {
                String defaultValue = rs.getString("Default");
                if(defaultValue == null || defaultValue.equals("")) {
                    defaultValue = "";
                }
                columnDefaultValue.add(defaultValue);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if(pStemt != null){
                try {
                    pStemt.close();
                    closeConnection(conn);
                } catch (SQLException e) {
                    LOGGER.error("getColumnComments close ResultSet and connection failure", e);
                }
            }

            if (rs != null) {
                try {
                    rs.close();
                    closeConnection(conn);
                } catch (SQLException e) {
                    LOGGER.error("getColumnComments close ResultSet and connection failure", e);
                }
            }
        }
        return columnDefaultValue;
    }

    /**
     * 获取字段设置的默认值
     * @param tableName
     * @return
     */
    public static List<String> getAttribute(String tableName) {
        List<String> columnAttribute = new ArrayList<>();
        //与数据库的连接
        Connection conn = getConnection();
        PreparedStatement pStemt = null;
        String tableSql = SQL + tableName;
        ResultSet rs = null;
        try {
            pStemt = conn.prepareStatement(tableSql);
            rs = pStemt.executeQuery("show full columns from " + tableName);
            while (rs.next()) {
                String attribute = rs.getString("Extra");
                if(attribute == null || attribute.equals("")) {
                    attribute = "";
                }
                columnAttribute.add(attribute);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if(pStemt != null){
                try {
                    pStemt.close();
                    closeConnection(conn);
                } catch (SQLException e) {
                    LOGGER.error("getColumnComments close ResultSet and connection failure", e);
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                    closeConnection(conn);
                } catch (SQLException e) {
                    LOGGER.error("getColumnComments close ResultSet and connection failure", e);
                }
            }
        }
        return columnAttribute;
    }
    /**
     * 获取表中字段的所有注释
     * @param tableName
     * @return
     */
    public static List<String> getColumnComments(String tableName) {
        //与数据库的连接
        Connection conn = getConnection();
        PreparedStatement pStemt = null;
        String tableSql = SQL + tableName;
        List<String> columnComments = new ArrayList<>();//列名注释集合
        ResultSet rs = null;
        try {
            pStemt = conn.prepareStatement(tableSql);
            rs = pStemt.executeQuery("show full columns from " + tableName);
            while (rs.next()) {
                columnComments.add(rs.getString("Comment"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if(pStemt != null){
                try {
                    pStemt.close();
                    closeConnection(conn);
                } catch (SQLException e) {
                    LOGGER.error("getColumnComments close ResultSet and connection failure", e);
                }
            }

            if (rs != null) {
                try {
                    rs.close();
                    closeConnection(conn);
                } catch (SQLException e) {
                    LOGGER.error("getColumnComments close ResultSet and connection failure", e);
                }
            }
        }
        return columnComments;
    }
    public static void main(String[] args) throws IOException {
        List<String> tableNames = getTableNames();
        //每10张表 组成一个excel
        //使用poi
        //七列
        //No 名称 类型 非空 默认值 属性 备注
        String[] headerName = {"No","名称","类型","非空","默认值","属性","备注"};

        HSSFWorkbook wb = new HSSFWorkbook();
        int f = 0;
        for (int i = 0; i < tableNames.size(); i++) {
            String tableName = tableNames.get(i);
            //每个sheet写成表名
            HSSFSheet sheet = wb.createSheet();
            wb.setSheetName(f, tableName);

            HSSFRow row = sheet.createRow(0);
            HSSFCellStyle style = wb.createCellStyle();
            HSSFCell cell = null;

            List<String> columnNames = getColumnNames(tableName);
            List<String> columnTypes = getColumnTypes(tableName);
            List<String> columnIsNull = getColumnIsNull(tableName);
            List<String> defaultValues = getDefaultValue(tableName);
            List<String> attributes = getAttribute(tableName);
            List<String> comments = getColumnComments(tableName);
            List<String> nos = new ArrayList<>();
            for (int p = 0; p < columnNames.size(); p++) {
                nos.add(String.valueOf(p+1));
            }

            List<List<String>> data = new ArrayList<>();
            data.add(nos);
            data.add(columnNames);
            data.add(columnTypes);
            data.add(columnIsNull);
            data.add(defaultValues);
            data.add(attributes);
            data.add(comments);

            for (int j = 0; j < headerName.length; j++) {
               // sheet.autoSizeColumn(j, true);
                cell = row.createCell(j);
                //第一行 为标题
                cell.setCellValue(headerName[j]);
                cell.setCellStyle(style);
            }

            for (int m = 0; m < columnNames.size(); m++) {
                HSSFRow rowData = sheet.createRow(m + 1);
                for (int n = 0; n < headerName.length; n++) {
                    HSSFCell cellData = rowData.createCell(n);
                    cellData.setCellValue(data.get(n).get(m));
                    cellData.setCellStyle(style);
                }
            }

            for (int k = 0; k < headerName.length; k++) {
                sheet.autoSizeColumn(k);
            }
            // 处理中文不能自动调整列宽的问题
            //this.setSizeColumn(sheet, dataStrList.size());
            //第二行开始填充数据
            // String ColumnNames = getColumnNames(tableName);
            f++;
            if ((i+1) % 10 == 0 || i == tableNames.size() - 1) {
                //每10张表换一个excel
                String filepath = "D:\\exceldata\\";
                String filename = i+".xls";
                FileOutputStream output=new FileOutputStream(filepath + filename);
                wb.write(output);//写入磁盘
                output.close();
                wb = new HSSFWorkbook();
                f = 0;
            }


        }

    }
}
